package file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.BitSet;
import java.util.Date;

import trigest.trigest;

/** 
 * Represent a local file shared with other peers.
 *
 */
public class LocalSharedFile {

	private String string_signature = "";
	private File file;
	private String abstraction = ""; 
	
	
	/**
	 * Construct a #LocalSharedFile
	 * @param path	path to find the file.
	 */
	public LocalSharedFile(String path)
	{
		this.setPath(path);
	}

	/**
	 * @param path the path to set
	 */
	private void setPath(String path) {
		this.setFile(new File(path));
	}

	/**
	 * @return the path
	 */
	public String getPath() {
		return this.getFile().getAbsolutePath();
	}

	/**
	 * @return the signature
	 * @throws IOException 
	 */
	public String signature() throws IOException {
		if(string_signature.isEmpty())
			this.calculateSignature();
		return string_signature;
	}

	/**
	 * Calculate file signature.
	 * @throws IOException 
	 */
	private void calculateSignature() throws IOException {
		BufferedReader is = new BufferedReader(new FileReader(this.getPath()));
		
		boolean abs_done = false;
		
		String line = is.readLine();
		while(line != null)
		{
	        String[] words = line.split("\\s+");
			for(String s : words)
			{
				//Get abstraction
				if(!abs_done)
				{
					if(abstraction.length() + s.length() + 1 > 100)
						abs_done = true;
					else
						abstraction += s + " ";
				}				
			}	
						
			line = is.readLine();
		}
		
		is.close();
		
		try {
			trigest d2= new trigest(this.getFile());
			byte[] sig = d2.getSignature();
//			for(byte b : sig)
//			{
//				this.string_signature += String.format("%02x", b);
//			}
			
			this.string_signature = fromByteArray(sig).toString();
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
	}
	
	private static BitSet fromByteArray(byte[] bytes) {
		BitSet bits = new BitSet();
		for (int i=0; i<bytes.length*8; i++) {
			if ((bytes[bytes.length-i/8-1]&(1<<(i%8))) > 0) {
				bits.set(i);
			}
		}
		return bits;
	}
	
	public String lastModified()
	{
		long last = getFile().lastModified();
		
		return util.DateTime.DateToString(new Date(last));
	}


	/**
	 * @return the abstraction of a file.
	 * @throws IOException 
	 */
	public String abstraction() throws IOException {
		if(abstraction.isEmpty())
			this.calculateSignature();
		return abstraction;
	}

	public String name() {
		return this.getFile().getName();
	}

	public long length() {
		return this.getFile().length();
	}

	/**
	 * @param file the file to set
	 */
	private void setFile(File file) {
		this.file = file;
	}

	/**
	 * @return the file
	 */
	public File getFile() {
		return file;
	}
}
